package sort;

/**
 * @Author: wangliuyang
 * @Date: 2021/8/5 09:30
 * @Description:归并排序
 */
public class MergeSort {
    public static void mergeSort1(int[] arr) {
        if (arr == null || arr.length == 1) {
            return;
        }
        mergesort(arr, 0, arr.length - 1);
    }

    private static void mergesort(int[] arr, int left, int right) {
        if (left == right) return;
        int mid = left + (right - left) >> 2;
        mergesort(arr, left, mid);
        mergesort(arr, mid + 1, right);
        merge(arr, left, right, mid);
    }

    private static void merge(int[] arr, int left, int right, int mid) {
        int[] tmp = new int[right - left + 1];
        int i = 0;
        int j = mid + 1;
        int index = 0;//记录新开辟数组赋值得位置
        while (i <= mid && j <= right) {
            tmp[index++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }
        while (i <= mid) {
            tmp[index++] = arr[i++];
        }
        while (j <= right) {
            tmp[index++] = arr[j++];
        }
        for (i = 0; i < tmp.length; i++) {
            arr[left + i] = tmp[i];
        }
    }
}
